#!/bin/bash
if [ -z "${MountPoint}" ]; then
    jenkinsHome="/home/hzz_jenkins"
    source "${jenkinsHome}/common/0_env.sh"
fi
alias vdbench='/root/vdbench50407/vdbench'

# arg1:dir arg2:num
function touch_many_file()
{
    dir=$1
    filenum=$2
    if (( $# != 2)); then 
        echo "touch file error!"; return 1; 
    else
        echo -e "\tcreate ${filenum} file in ${dir}/"
    fi

    for ((i=0; i<${filenum}; i++)); do
        touch "${dir}"/file$i
    done

    # 实际测试发现，创建文件后，需要等待一定时间，目录的大小才会更新
    sleep 1
}

# arg1:parent_dir arg2:num
function create_many_dir()
{
    parentdir=$1
    dirnum=$2
    if (( $# != 2)); then 
        echo "mkdir error!"; return 1; 
    else
        echo -e "\tcreate ${dirnum} subdir in ${parentdir}/"
    fi

    for ((i=0; i<${dirnum}; i++)); do
        mkdir -p "${parentdir}"/subdir$i
    done

    # 实际测试发现，创建文件后，需要等待一定时间，目录的大小才会更新
    sleep 1
}

function clean_dir() {
    dir_path=`realpath "$1"`
    echo -e "\n\t清空目录 ${dir_path}"
    if [ "${dir_path}" == "/" ]; then
        echo "clean Dir: ${dir_path} is root"
    else
        rm -rf "${dir_path:?}"/*
    fi

    # 实际测试发现，创建文件或删除文件后，需要等待一定时间，其父目录的大小才会更新
    sleep 1
}

function test_cmd()
{
    if (($# != 1)); then echo "Invalid args num"; return 1; fi

    cmd="$1"
    echo -e -n "\t>>> $cmd --> "
    if eval ${cmd} > /tmp/cmdout; then
        echo "Ok"
        if [ -s "/tmp/cmdout" ]; then # 文件存在且非大小非 0
            echo -e -n "\t    "
            cat /tmp/cmdout
        fi
        rm -f /tmp/cmdout
        return 0;
    else
        echo "Exec falided"
        rm -f /tmp/cmdout
        return 1;
    fi
}

function test_cmd_nohup()
{
    if (($# != 1)); then echo "Invalid args num"; return 1; fi

    cmd="$1"
    echo -e "\t>>> $cmd"
    eval ${cmd} &
}

function test_error_cmd()
{
    if (($# != 1)); then echo "Invalid args num"; return 1; fi

    cmd="$1"
    echo -e "\t>>> $cmd"
    if eval ${cmd}; then
        echo -e "\tError: 异常成功"
        return 1;
    else
        return 0;
    fi
}

function rm_abs_dir() {
    dir_path=`realpath "$1"`
    #dir_path=`realpath ${MountPoint}/$1`
    echo -e "\n删除目录 ${dir_path}"
    if [ "${dir_path}" == "/" ]; then
        echo "clean Dir: ${dir_path} is root"
        return 1
    else
        rm -rf "${dir_path:?}"/
    fi
}

# dirName="$1" caseFile="$2"
function exec_vdbench()
{
    echo -e "\n构造 vdbench 数据 $1"

    if (($# != 2)); then echo "Invalid args num"; return 1; fi
    dirName="$1"
    caseFile="$2"

    if ! grep "${dirName}" "${caseFile}"; then
        echo "dirname in vdbench case file may be error"
        return 1;
    fi

    "${vdbenchPath}"/vdbench -f "${caseFile}" &> /tmp/test_du_vdbench.log
}

function print3s()
{
    echo -e "\n   # $*"
}

function exec_tree()
{
    tree "$@"  | grep -v "directory" | grep -v "directories" > /tmp/cmdout
    awk '{print "        "$0}' /tmp/cmdout
}